package web;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import mbank.Account;
import mbank.ClientActions;
import mbank.Customer;
import mbank.DBManagerException;
import mbank.GeneralReports;
import mbank.MBank;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MBank bank = null;

	public void init(ServletConfig config) throws ServletException {

		super.init(config);
		System.getProperties().setProperty("invokeThreads", "FALSE");

		try {
			bank = MBank.getInstance();
			getServletConfig().getServletContext().setAttribute(Const.MBANK,
					bank);
		} catch (DBManagerException e) {
			e.printStackTrace();
		}

	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Login Servlet : Service");
		String page = null;
		ClientActions clientActions = null;
		long id_userConvert = 0;
		long passwordConvert = 0;

		String password = (String) request.getParameter(Const.PASSWORD);
		String id_user = (String) request.getParameter(Const.ID_USER);

		if ((password == null || password.length() < 1)
				|| (id_user == null || id_user.length() < 1)) {

			page = "/index.jsp";

			this.getServletContext().getRequestDispatcher(page).forward(
					request, response);
			return;

		} else {
			try {
				id_userConvert = Long.valueOf(id_user);
				passwordConvert = Long.valueOf(password);
				clientActions = bank.clientLogin(id_userConvert,
						passwordConvert);

			} catch (Exception e) {
				System.out.println("input not right");
			}

		}

		HttpSession session = request.getSession(true);

		if (clientActions != null) {
			page = "/main.jsp";
			session.setAttribute(Const.CLIENT_ACTIONS, clientActions);
			session.setAttribute(Const.ID_USER, id_userConvert);
			session.setAttribute(Const.PASSWORD, passwordConvert);

			try {
				Customer customer = clientActions
						.getCustomerById(id_userConvert);
				Account account = clientActions.getAccountById(customer
						.getCustId());
				session.setAttribute(Const.CUSTOMER, customer);
				session.setAttribute(Const.ACCOUNT, account);

			} catch (DBManagerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {
			page = "/error.jsp";
		}
		this.getServletContext().getRequestDispatcher(page).forward(request,
				response);
	}

}
